package net.huashitong.synthetical.showView.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

import static com.alibaba.fastjson.JSON.parseObject;
import static net.huashitong.synthetical.showView.util.DataFormateUntil.dataFormat;
import static net.huashitong.synthetical.showView.util.DataTimeUtil.strToDateFormat;
import static net.huashitong.synthetical.showView.util.HttpsUtils.doGet;
import static net.huashitong.synthetical.showView.util.ProgressStatic.getProgress2;
import static net.huashitong.synthetical.showView.util.ProgressStatic.stageList;
import static net.huashitong.synthetical.showView.util.URLstatic.*;
import static net.huashitong.synthetical.showView.util.commonUtil.strDealWith;

@Service
public class SyntheService {

    Logger log = LoggerFactory.getLogger(SyntheService.class);

    /**
     * 重大项目进程报告（总完成任务情况）接口
     *
     * @param url
     * @param params
     * @return
     */
    public Map<String, Object> getProjectSchedule(String url, String url2, Map<String, Object> params) {
        //重大项目进程报告（总完成任务情况）接口
        String code = "500";
        String code2 = "500";
        JSONObject jsonObject1;
        JSONObject jsonObject2;
        Map<String, Object> params2 = new HashMap<>();
        try {
            jsonObject1 = doGet(url, params);
            jsonObject2 = doGet(url2, params2);
            code = jsonObject1.getString("code");
            code2 = jsonObject2.getString("code");
        } catch (Exception e) {
            log.info("--------------------------没有查询到此项目-------------------------------");
            System.out.println("没有查询到此项目");    //打印异常信息
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("planTimes", "-");
            resMap.put("factTimes", "-");
            resMap.put("nodes", "-");
            resMap.put("timeStates", "-");
            resMap.put("node1Names", "-");
            resMap.put("countFinishDays", "-");
            resMap.put("earlyFinishedDays", "-");
            return resMap;
        }
        if ("200".equals(code) && "200".equals(code2)) {
            //获取成功
            JSONObject object = jsonObject1.getJSONObject("data");
            //总耗时
            String countFinishDays = object.getString("countFinishDays");
            String earlyFinishedDays = object.getString("earlyFinishedDays");
            String text = object.getJSONObject("nodes").toJSONString();
            Map<String, Object> map = parseObject(text, TreeMap.class);

            List<String> planTimes = new ArrayList<>();
            List<String> factTimes = new ArrayList<>();
            List<String> nodes = new ArrayList<>();
            //逾期情况---正数表示超前；0表示正常；负数表示逾期
            List<String> timeStates = new ArrayList<>();
            List<String> nodeNames = new ArrayList<>();

            //时间进度表（招商部分）
            JSONObject object2 = jsonObject2.getJSONObject("data");
            JSONArray jsonArray = object2.getJSONArray("process");
            List<Map<String, Object>> progressList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jo = JSONObject.parseObject(jsonArray.get(i).toString());
                Map<String, Object> progressMap = parseObject(jo.toJSONString(), TreeMap.class);
                nodes.add((String) progressMap.get("stage"));
                planTimes.add("-");
                factTimes.add("-");
                timeStates.add("-");
                nodeNames.add("-");
            }


            for (Object in : map.keySet()) {
                Map<String, Object> oneMap = parseObject(map.get(in).toString(), HashMap.class);
//                Map<String,String> oneMap =(HashMap<String, String>) map.get(in);//得到每个key多对用value的值
                planTimes.add(oneMap.get("planTime").toString());
                factTimes.add(oneMap.get("factTime").toString());
                nodes.add(oneMap.get("nodeId").toString());
                //逾期情况
                if (oneMap.get("timeState").toString().contains("-") && !"0".equals(oneMap.get("timeState").toString())) {
                    timeStates.add(oneMap.get("timeState").toString().replace("-", ""));
                } else {
                    timeStates.add("--");
                }
                nodeNames.add(oneMap.get("node1Name").toString());
            }
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("planTimes", planTimes);
            resMap.put("factTimes", factTimes);
            resMap.put("nodes", nodes);
            resMap.put("timeStates", timeStates);
            resMap.put("nodeNames", nodeNames);
            resMap.put("countFinishDays", StringUtils.isBlank(countFinishDays) ? "0" : countFinishDays);
            resMap.put("earlyFinishedDays", StringUtils.isBlank(earlyFinishedDays) ? "0" : earlyFinishedDays);
            return resMap;
        } else {
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("planTimes", "-");
            resMap.put("factTimes", "-");
            resMap.put("nodes", "-");
            resMap.put("timeStates", "-");
            resMap.put("node1Names", "-");
            resMap.put("countFinishDays", "-");
            resMap.put("earlyFinishedDays", "-");
            return resMap;
        }
    }

    /**
     * 项目进度时间
     *
     * @param url
     * @param params
     * @return
     */
    public Map<String, Object> getProjectProgressTime(String url, Map<String, Object> params) {
        String code = "500";
        JSONObject jsonObject;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");
        } catch (Exception e) {
            log.info("--------------------------没有查询到此项目-------------------------------");
            System.out.println("没有查询到此项目");    //打印异常信息
            Map<String, Object> resMap1 = new HashMap<>();
            resMap1.put("projectName", "-");
            resMap1.put("beginTime", "-");
            resMap1.put("endTime", "-");
            resMap1.put("useTime", "-");
            resMap1.put("planTime", "-");
            resMap1.put("percent", "-");
            return resMap1;
        }

        if ("200".equals(code)) {
            //获取成功
            JSONObject object = jsonObject.getJSONObject("data");
            String beginTime = object.getString("beginTime");       //洽谈开始时间
            String endTime = object.getString("endTime");           //计划投产时间
            String useTime = object.getString("factTime");          //在建耗时（实际用时）
            String planTime = object.getString("planTime");         //计划总用时
            String projectName = object.getString("projectName");   //项目名称
            double u = Double.parseDouble(useTime);
            double p = Double.parseDouble(planTime);
            String percent = dataFormat(u / (p == 0 ? 1.0 : p) * 100 + "") + "%";                     //占比
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("projectName", projectName);
            resMap.put("beginTime", beginTime);
            resMap.put("endTime", endTime);
            resMap.put("useTime", useTime);
            resMap.put("planTime", planTime);
            resMap.put("percent", percent);
            return resMap;
        } else {
            Map<String, Object> resMap1 = new HashMap<>();
            resMap1.put("projectName", "-");
            resMap1.put("beginTime", "-");
            resMap1.put("endTime", "-");
            resMap1.put("useTime", "-");
            resMap1.put("planTime", "-");
            resMap1.put("percent", "-");
            return resMap1;
        }
    }

    /**
     * 详细页面项目基本情况
     *
     * @param url
     * @param params
     * @return
     */
    public Map<String, Object> getbasesituation(String url, Map<String, Object> params) throws ParseException {
        String code = "500";
        JSONObject jsonObject;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");
        } catch (Exception e) {
            log.info("--------------------------项目基本情况数据错误-------------------------------");
            System.out.println("项目基本情况数据错误");    //打印异常信息
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("projectClass", "-");            //项目类别
            resMap.put("projectStage", "-");            //项目阶段
            resMap.put("projectName", "-");             //项目名称
            resMap.put("investorName", "-");            //投资方名称
            resMap.put("projectManager", "-");          //负责人
            resMap.put("totalInver", "-");              //总额
            resMap.put("attribute", "-");               //三维属性，国企，民企，外企
            return resMap;
        }

        if ("200".equals(code)) {
            //获取成功
            JSONObject object = jsonObject.getJSONObject("data");
            String text = object.getJSONObject("info").toJSONString();
            Map<String, Object> map = parseObject(text, TreeMap.class);
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("projectClass", strDealWith(map.get("projectClass")));        //项目类别
            resMap.put("projectStage", strDealWith(map.get("projectStage")));        //项目阶段
            resMap.put("projectName", strDealWith(map.get("projectName")));          //项目名称
            resMap.put("investorName", strDealWith(map.get("investorName")));        //投资方名称
            resMap.put("projectManager", strDealWith(map.get("projectManager")));    //负责人
            resMap.put("totalInver", strDealWith(map.get("totalInver")));            //总额
            resMap.put("attribute", strDealWith(map.get("attribute")));              //三维属性，国企，民企，外企

            JSONArray jsonArray = object.getJSONArray("process");
            List<Map<String, Object>> progressList = new ArrayList<>();
            List<String> stageList = stageList();
            for(String stage : stageList){

                boolean flag = false;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = JSONObject.parseObject(jsonArray.get(i).toString());
                    Map<String, Object> progressMap = parseObject(jo.toJSONString(), TreeMap.class);
                    if(stage.equals(progressMap.get("stage"))){
                        progressMap.put("resUser", resMap.get("projectManager"));
                        progressMap.put("projectState", "已完成");
                        progressMap.put("nodeTime", "-");
                        progressMap.put("datetime",strToDateFormat((String) progressMap.get("datetime")));
                        progressList.add(progressMap);
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    Map<String,Object> proMap = new HashMap<>();
                    proMap.put("stage",stage);
                    proMap.put("resUser","-");
                    proMap.put("projectState", "-");
                    proMap.put("nodeTime", "-");
                    proMap.put("datetime","-");
                    progressList.add(proMap);
                }
            }

            resMap.put("progress1", progressList);
            return resMap;

        } else {
            Map<String, Object> resMap = new HashMap<>();
            resMap.put("projectClass", "-");            //项目类别
            resMap.put("projectStage", "-");            //项目阶段
            resMap.put("projectName", "-");             //项目名称
            resMap.put("investorName", "-");            //投资方名称
            resMap.put("projectManager", "-");          //负责人
            resMap.put("totalInver", "-");              //总额
            resMap.put("attribute", "-");               //三维属性，国企，民企，外企
            return resMap;
        }

    }


    public List<Map<String, Object>> getBuildProgress(String projectId) {
        //在建阶段（完成情况）
        String url = GET_FINISH_DETAIL;
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        String code = "500";
        JSONObject jsonObject = null;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");

        } catch (Exception e) {
            log.info("--------------------------项目完成情况数据错误-------------------------------");
        }
        List<Map<String, Object>> resList = new ArrayList<>();
        List<Map<String, Object>> resList2 = new ArrayList<>();
        if ("200".equals(code)) {
            //获取成功
            JSONObject object = jsonObject.getJSONObject("data");

            String text = object.getJSONObject("nodes").toJSONString();
            Map<String, Object> map = parseObject(text, TreeMap.class);
            for (Object node : map.keySet()) {
                Map<String, Object> nodeMap = parseObject(map.get(node).toString(), HashMap.class);
                Map<String, Object> map1 = new HashMap<>();
                map1.put("stage", nodeMap.get("node1Name"));
                map1.put("projectState", "已完成");
                map1.put("projectId", nodeMap.get("projectId"));
                map1.put("nodeId", nodeMap.get("nodeId"));

//                //添加节点信息
//                Map<String, Object> param = new HashMap<>();
//                param.put("nodeId", nodeMap.get("nodeId"));
//                param.put("projectId", nodeMap.get("projectId"));
//
//                JSONObject jsonOb = doGet(GET_NODE_DETAIL, param);
//                JSONObject object1 = jsonOb.getJSONObject("data");
//                String strJsonObj = object1.getJSONArray("smallNodes").get(0).toString();
//                Map<String, Object> smallNode = parseObject(strJsonObj, HashMap.class);
//                map1.put("resUser", smallNode.get("resUser"));
//                map1.put("nodeTime", smallNode.get("factFinishDate"));
//                map1.put("nodeTime", smallNode.get("factTime"));

                resList.add(map1);
            }
            List<String> strList = getProgress2();
            for (Map<String, Object> m : resList) {
                String node1Name = (String) m.get("stage");
                for (String str : strList) {
                    if (node1Name.contains(str)) {
                        resList2.add(m);
                        break;
                    }
                }
            }
            return resList2;
        } else {
            return resList2;
        }
    }

    /**
     * 获取项目预警等级s数量
     * @param projectId
     * @return
     */
    public JSONObject warningnumbers(String projectId){
        String url = EARLY_WARNING_NUMBER;
        //添加节点信息
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        String code = "500";
        JSONObject jsonObject = null;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");

        } catch (Exception e) {
            log.info("--------------------------项目完成情况数据错误-------------------------------");
            return null;
        }
        if ("200".equals(code)) {
            //获取成功
            JSONObject object = jsonObject.getJSONObject("data");
            return object;
        }else{
            return null;
        }
    }


    /**
     * 获取预警详情
     * @param projectId
     * @return
     */
    public JSONArray warningdetail(String projectId,String level){
        String url = EARLY_WARNING_DETAILS;
        //添加节点信息
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        params.put("level", level);

        String code = "500";
        JSONObject jsonObject = null;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");

        } catch (Exception e) {
            log.info("--------------------------项目完成情况数据错误-------------------------------");
            return null;
        }
        if ("200".equals(code)) {
            //获取成功
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            return jsonArray;
        }else{
            return null;
        }
    }



    /**
     * 获取指定项目所有预警列表
     * @param projectId
     * @return
     */
    public JSONArray warningshort(String projectId){
        String url = EARLY_WARNING_SHORT;
        //添加参数
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        String code = "500";
        JSONObject jsonObject = null;
        try {
            jsonObject = doGet(url, params);
            code = jsonObject.getString("code");

        } catch (Exception e) {
            log.info("--------------------------项目完成情况数据错误-------------------------------");
            return null;
        }
        if ("200".equals(code)) {
            //获取成功
            JSONArray array = jsonObject.getJSONArray("data");
            return array;
        }else{
            return null;
        }
    }


}
